package com.calvin.study.base;

import com.alibaba.fastjson.JSON;
import com.calvin.study.exception.CustomException;
import com.calvin.study.exception.CustomExceptionType;

import lombok.Data;

@Data
public class ResponseModel {
	

	private boolean isOk; // 请求是否处理成功

	private int code; // 请求响应状态码（200、400、500）

	private String message; // 请求结果描述信息

	private Object data; // 请求结果数据（通常用于查询操作）
	
	private ResponseModel() {
	}

	// 请求出现异常时的响应数据封装
	public static ResponseModel error(CustomException e) {
		ResponseModel resultBean = new ResponseModel();
		resultBean.setOk(false);
		resultBean.setCode(e.getCode());
		resultBean.setMessage(e.getMessage());
		return resultBean;
	}

	// 请求出现异常时的响应数据封装
	public static ResponseModel error(CustomExceptionType customExceptionType, String errorMessage) {
		ResponseModel resultBean = new ResponseModel();
		resultBean.setOk(false);
		resultBean.setCode(customExceptionType.getCode());
		resultBean.setMessage(errorMessage);
		return resultBean;
	}
	
	public static ResponseModel error(String errorMessage) {
		ResponseModel resultBean = new ResponseModel();
		resultBean.setOk(false);
		resultBean.setCode(CustomExceptionType.SYSTEM_ERROR.getCode());
		resultBean.setMessage(errorMessage);
		return resultBean;
	}

	// 请求成功的响应，不带查询数据（用于删除、修改、新增接口）
	public static ResponseModel success() {
		ResponseModel ResponseModel = new ResponseModel();
		ResponseModel.setOk(true);
		ResponseModel.setCode(200);
		ResponseModel.setMessage("请求响应成功!");
		return ResponseModel;
	}

	// 请求成功的响应，带有查询数据（用于数据查询接口）
	public static ResponseModel success(Object obj) {
		ResponseModel ResponseModel = new ResponseModel();
		ResponseModel.setOk(true);
		ResponseModel.setCode(200);
		ResponseModel.setMessage("请求响应成功!");
		ResponseModel.setData(obj);
		return ResponseModel;
	}

	// 请求成功的响应，带有查询数据（用于数据查询接口）
	public static ResponseModel success(Object obj, String message) {
		ResponseModel ResponseModel = new ResponseModel();
		ResponseModel.setOk(true);
		ResponseModel.setCode(200);
		ResponseModel.setMessage(message);
		ResponseModel.setData(obj);
		return ResponseModel;
	}
	
	public String toJson() {
		return JSON.toJSONString(this);
	}
	
	public static void main(String[] args) {
		System.out.println(ResponseModel.error("123123").toJson());
		System.out.println(ResponseModel.error(new CustomException(CustomExceptionType.USER_INPUT_ERROR, "用户名或者密码不能为空")));
	}

}
